package com.itheima.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.Pojo.Employee;
import com.itheima.Service.EmployeeService;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    //把service注入
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录功能
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request,@RequestBody Employee employee){
        //1.将密码用md5加密
        String password= employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.判断用户是否存在，根据用户提供的用户名username查询数据库
        LambdaQueryWrapper<Employee> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee employeeServiceOne = employeeService.getOne(lambdaQueryWrapper);

        //3.如果没有查询到返回结果为失败
        if(employeeServiceOne==null){
            return R.error("用户不存在");
        }

        //4.密码比对 如果不一致返回登录失败的结果
        if(!password.equals(employeeServiceOne.getPassword())){
            return R.error("密码错误，请重试");
        }

        //5.查看员工状态，是否被禁用
        if(employeeServiceOne.getStatus()==0){
            return R.error("您的账号已被禁用");
        }

        //6.登录成功，将员工id存取到session中返回成功结果
        request.getSession().setAttribute("employee",employeeServiceOne.getId());
        return R.success(employeeServiceOne);
    }

    /**
     * 员工退出功能
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理session中保存的当前登录员工id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 增加员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        //设置初始密码，并用md5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置创建时间，修改时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获得当前用户的Id
        int empId = (int) request.getSession().getAttribute("employee");
        //设置创建人
        employee.setCreateUser((long) empId);
        employee.setUpdateUser((long) empId);

        //将页面数据加载到数据库中
        employeeService.save(employee);

        return R.success("新增员工成功");
    }

    /**
     * 按照条件查询员工列表，并进行分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={}，pageSize={},name={}",page,pageSize,name);
        //构建分页构造器
        Page pageInfo=new Page(page,pageSize);
        //构造条件查询器
        LambdaQueryWrapper<Employee> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //添加过滤条件
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo,lambdaQueryWrapper);

        return R.success(pageInfo);
    }

    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        int empId= (int) request.getSession().getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((long) empId);
        employeeService.updateById(employee);
        return R.success("员工修改成功");
    }

    /**
     * 根据id查询员工id
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee=employeeService.getById(id);
        if(employee!=null){
            return R.success(employee);
        }
        return R.error("没有此员工");
    }
}
